package com.java.framework.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.java.common.utils.tool.ServletUtils;
import com.java.framework.interceptor.annotation.LoginValidate;
import com.java.framework.web.domain.AjaxResult;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 登录校验拦截器：
 * 凡是方法头部加了注解@LoginValidate的controller，执行前都会先执行下面的preHandle()方法
 *
 */
@Component
public abstract class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            LoginValidate annotation = method.getAnnotation(LoginValidate.class);
            if (annotation != null) {
                if (!this.isLogin(request)) {
                    AjaxResult ajaxResult = AjaxResult.error("未登录，请先登录");
                    ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult));
                    return false;
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }

    /**
     * 验证是否登录由子类实现具体的规则
     *
     * @param request
     * @return
     * @throws Exception
     */
    public abstract boolean isLogin(HttpServletRequest request);
}
